<?php

namespace backend\controllers;

use backend\models\PasswordForm;
use common\models\batch\UserBatch;
use common\models\search\UserSearch;
use common\models\User;
use Yii;
use yii\filters\VerbFilter;
use yii\web\NotFoundHttpException;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends BaseController
{
    public function behaviors()
    {
        return array_merge(parent::behaviors(),
            [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
                        'delete' => ['post'],
                    ],
                ],
            ]);
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $batchModel = new UserBatch();
        if (isset($_POST['id'])) {
            $result = $batchModel->process($_POST['id'], $_POST);
            if (is_string($result)) {
                Yii::$app->getSession()->setFlash('success', $result);
                return $this->redirect(Yii::$app->getRequest()->getAbsoluteUrl());
            }
        }

        $searchModel = new UserSearch();

        return $this->render('index', [
            'dataProvider' => $searchModel->search($_GET),
            'searchModel' => $searchModel,
            'batchModel' => $batchModel,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $this->menuRoute = false;
        $model = new User(['scenario' => 'create']);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', '用户创建成功。');
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        if ($id === Yii::$app->getUser()->getId()) {
            return $this->redirect(['profile']);
        }

        $model = $this->findModel($id);
        $passwordForm = new PasswordForm();
        $post = Yii::$app->request->post();

        if ($model->load($post) && $passwordForm->load($post) && $passwordForm->validate()) {
            if ($passwordForm->password) {
                $model->setPassword($passwordForm->password);
                $model->generateAuthKey();
            }
            if ($model->save()) {
                Yii::$app->session->setFlash('success', '用户更新成功。');
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

        return $this->render('update', [
            'model' => $model,
            'passwordForm' => $passwordForm,
        ]);
    }

    /**
     * @return string|\yii\web\Response
     */
    public function actionProfile()
    {
        $model = $this->findModel(Yii::$app->user->getId());
        $model->setScenario('profile');
        $passwordForm = new PasswordForm();
        $post = Yii::$app->request->post();

        if ($model->load($post) && $passwordForm->load($post) && $passwordForm->validate()) {
            if ($passwordForm->password) {
                $model->setPassword($passwordForm->password);
                $model->generateAuthKey();
            }

            if ($model->save()) {
                Yii::$app->session->setFlash('success', '个人资料更新成功。');
                return $this->redirect(['profile']);
            }
        }

        return $this->render('profile', [
            'model' => $model,
            'passwordForm' => $passwordForm,
        ]);
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete()
        &&
        Yii::$app->session->setFlash('success', '用户删除成功。');
        return $this->redirect(['index']);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
